package cn.mianshiyi.braumadmin.service;

import cn.mianshiyi.braumadmin.common.Constant;
import cn.mianshiyi.braumadmin.entity.LimiterDataEntity;
import cn.mianshiyi.braumadmin.mapper.LimiterDataMapper;
import cn.mianshiyi.braumadmin.utils.DateUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author shangqing.liu
 */
@Service
public class CleanLimiterDataExecute {

    public static ScheduledThreadPoolExecutor sendMessageExecutor = new ScheduledThreadPoolExecutor(1);

    @Resource
    private LimiterDataMapper limiterDataMapper;

    @Value("${easy.limiter.store.hour:#{null}}")
    private Integer storeHour;

    @PostConstruct
    public void start() {
        sendMessageExecutor.scheduleAtFixedRate(() -> {
            try {
                if (storeHour == null || storeHour > Constant.MAX_STORE_HOUR || storeHour < 0) {
                    storeHour = Constant.DEFAULT_STORE_HOUR;
                }
                Long cleanTime = DateUtil.add(new Date(), Calendar.HOUR, -storeHour).getTime() / 1000;
                List<LimiterDataEntity> cleanEntity = limiterDataMapper.findByCleanTime(cleanTime);
                if (CollectionUtils.isEmpty(cleanEntity)) {
                    return;
                }
                List<Long> cleanIds = cleanEntity.stream().map(LimiterDataEntity::getId).collect(Collectors.toList());
                List<List<Long>> partition = Lists.partition(cleanIds, 100);
                for (List<Long> ids : partition) {
                    limiterDataMapper.deleteByIdList(ids);
                }
            } catch (Exception e) {
            }
        }, 10000, 3000, TimeUnit.MILLISECONDS);
        System.out.println("clean limiter data start");
    }
}
